package com.ruoyi.web.admin.data.command;

import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.service.ISysDeviceCollectRecordService;
import com.ruoyi.system.service.ISysDeviceService;
import com.ruoyi.web.admin.data.Constants;
import com.ruoyi.web.admin.data.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 设备登录命令处理器
 *
 * @author 10100
 */
@Component
public class DeviceLoginCommandHandler implements CommandHandler {


    private static final Logger log = LoggerFactory.getLogger(DeviceLoginCommandHandler.class);

    @Value("${device.model}")
    private String deviceModel;

    @Resource
    private ISysDeviceService sysDeviceService;

    @Resource
    private ISysDeviceCollectRecordService sysDeviceCollectRecordService;

    @Override
    public String handle(String deviceId, String iccid, String recordId, String command,
                         String type, String timestamp, String length, String body) {
        log.info("设备[{}]登录请求", deviceId);

        // 更新设备连接状态为在线
        try {
            SysDevice device = sysDeviceService.selectSysDeviceByeIdentifier(deviceId);
            if (device != null) {
                // 1表示在线
                device.setConnectionStatus("1");
                device.setLastHeartbeatTime(new Date());
                sysDeviceService.updateSysDevice(device);
                log.info("设备[{}]状态已更新为在线", deviceId);

                sysDeviceCollectRecordService.insertRecord(device, "CONNECTION_STATUS", "1", "0离线 1在线");
            } else {
                // 设备不存在，创建新设备记录
                log.info("设备[{}]不存在，创建新设备记录", deviceId);
                SysDevice newDevice = getSysDevice(deviceId);
                try {
                    sysDeviceService.insertSysDevice(newDevice);
                    log.info("设备[{}]创建成功", deviceId);
                } catch (Exception ex) {
                    log.error("创建设备[{}]记录时发生错误: {}", deviceId, ex.getMessage(), ex);
                }
            }
        } catch (Exception e) {
            log.error("更新设备[{}]状态时发生错误: {}", deviceId, e.getMessage(), e);
        }

        // 构建响应格式
        String responseBody = "0@0@0";
        return "[" + deviceId + "," +
                iccid + "," +
                CommonUtils.generateSerialNumber() + "," +
                command + "," +
                Constants.REPORT_RESPONSE + "," +
                CommonUtils.getCurrentTimestamp() + "," +
                responseBody.length() + "," +
                responseBody + "]";
    }

    private SysDevice getSysDevice(String deviceId) {
        SysDevice newDevice = new SysDevice();
        newDevice.setDeviceIdentifier(deviceId);
        // 默认设备型号
        newDevice.setDeviceModel(deviceModel);
        // 0表示空闲
        newDevice.setDeviceStatus("0");
        // 1表示在线
        newDevice.setConnectionStatus("1");
        // 0表示未佩戴
        newDevice.setWearStatus("0");
        // 默认电量100%
        newDevice.setBatteryLevel(100);
        // 0表示正常
        newDevice.setFaultStatus("0");
        return newDevice;
    }

    @Override
    public String getCommandType() {
        return "DEVICE_LOGIN";
    }
}